package com.memoryangelapplication.services;

import java.security.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import com.memoryangelapplication.AlertMessageSinglePreview;
import com.memoryangelapplication.AlertMessageSinglePreview;
import com.memoryangelapplication.AlertMessageSinglePreviewTesting;
import com.memoryangelapplication.global.Event_pass;
import com.memoryangelapplication.model.EventObj;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.Toast;

public class EventAlarm extends WakefulBroadcastReceiver {

	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private String MEM_EVENT = "table_events";
    int timeout = 30;
	private Context passcontext;

	ArrayList<EventObj> lst = new ArrayList<EventObj>();

	private final String REMINDER_BUNDLE = "MyReminderBundle";

	String[] EventTitleArray;
	
	public EventAlarm() {
	}

	public EventAlarm(Context context, Bundle extras, int timeoutInSeconds) {
	
		passcontext = context;
		int xx= timeoutInSeconds;
		
		AlarmManager alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, EventAlarm.class);
		intent.putExtra(REMINDER_BUNDLE, extras);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);
		Calendar time = Calendar.getInstance();
		time.setTimeInMillis(System.currentTimeMillis());
		time.add(Calendar.SECOND, xx);

		/*
		 * alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
		 * time.getTimeInMillis(), 1000*1, pendingIntent);
		 */
		alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
				pendingIntent);

	}

	@Override
	public void onReceive(Context context, Intent intent) {
		//Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();

		String nowunixtime = getAddDateTimeString().toString();

		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		ContentValues newrowfDealer = new ContentValues();
		Cursor fdealerrows = null;

		try {
			/*fdealerrows = mydb.query(MEM_EVENT, null,
					"event_active = '0' AND event_alam_time < '" + nowunixtime
							+ "' AND event_status != '3'", null, null, null, null);*/
			String query = "SELECT * FROM table_events WHERE event_active !='3' AND event_alam_time < '"
					+ nowunixtime + "' AND event_active = '0' ORDER BY _id,event_alam_time ASC";
			fdealerrows = mydb.rawQuery(query, null);
			
			
			
		} catch (Exception e) {
		}

		if (fdealerrows != null) {
			if (fdealerrows.getCount() > 0) {
				EventTitleArray = new String[fdealerrows.getCount()];
				int i = 0;
				while (fdealerrows.moveToNext()) {
					Intent i2 = new Intent(context, AlertMessageSinglePreview.class);
					i2.putExtra("eventTimeStamp", fdealerrows.getString(20));
					i2.putExtra("eventDisplayIDFlag", "0");
					i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(i2);
/*					Intent i2 = new Intent(context, AlertMessageSinglePreview.class);
					i2.putExtra("event_id", fdealerrows.getString(0));//
					i2.putExtra("event_log_id", fdealerrows.getString(1));//
					i2.putExtra("event_user_id", fdealerrows.getString(2));//
					i2.putExtra("event_title", fdealerrows.getString(3));// 
					i2.putExtra("event_description", fdealerrows.getString(4));//
					i2.putExtra("event_status", fdealerrows.getString(5));//
					i2.putExtra("event_date", fdealerrows.getString(6));//
					i2.putExtra("event_time", fdealerrows.getString(7));//
					i2.putExtra("event_alam_time", fdealerrows.getString(8));//
					i2.putExtra("event_active", fdealerrows.getString(9));//
					i2.putExtra("event_user_phoneno", fdealerrows.getString(10));
					i2.putExtra("event_url", fdealerrows.getString(11));
					i2.putExtra("event_package", fdealerrows.getString(12));
					i2.putExtra("event_time_stamp", fdealerrows.getString(13));
					i2.putExtra("event_update_time", fdealerrows.getString(14));
					i2.putExtra("event_ack_count", fdealerrows.getString(15));
					i2.putExtra("eventReminderTime", fdealerrows.getString(16));//
					i2.putExtra("eventReminderNumber", fdealerrows.getString(17));//
					i2.putExtra("eventWaitTime", fdealerrows.getString(18));//
					i2.putExtra("eventNotifyType", fdealerrows.getString(19));
					i2.putExtra("eventTimeStamp", fdealerrows.getString(20));
					i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(i2);
					i++;*/
					
					/*String CurrentTitle =  fdealerrows.getString(3);
					EventTitleArray[i] = CurrentTitle;
					i++;  */ 
					   
				}

			} else {

			}
		}
		mydb.close();
	}

	private void runOnUiThread(Runnable runnable) {
		// TODO Auto-generated method stub

	}

	public class AlertUI extends AsyncTask<String, Void, String> {
		private Context asynccontext;
		public AlertUI(Context passContext) {
			super();
			asynccontext = passContext;
		}

		@Override
		protected String doInBackground(String... urls) {

			for (int i = 0; i < lst.size(); i++) {
				EventObj mth = (EventObj) lst.get(i);

				Intent i2 = new Intent(asynccontext, AlertMessageSinglePreview.class);

				i2.putExtra("event_title", mth.getEvent_title());
				i2.putExtra("event_date", mth.getEvent_date());
				i2.putExtra("event_time", mth.getEvent_time());
				i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				asynccontext.startActivity(i2);

			}
			return null;
		}

	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("yyyy-MM-dd");
		String date_to_string = ddMMMyyFormat.format(c.getTime());
		return date_to_string;
	}

	private String getCurrentTimeStringTime() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("hh:mm a");
		String date_to_string = ddMMMyyFormat.format(c.getTime());
		return date_to_string;
	}

}
